<template>
  <div class="page_set page-miH page-bgBack">
    <a-form layout="inline" class="formrow" :form="searchForm" :colon="true">
      <div>
        <a-form-item>
          <a-input-search
            v-decorator="['title', { rules: [{ required: false, message: '请选择' }] }]"
            style="width: 240px"
            placeholder="关键字搜索"
            :allow-clear="true"
            @search="searchContarct"
          />
        </a-form-item>
        <a-form-item>
          <a-select
            v-decorator="['status', { rules: [{ required: false, message: '请选择' }] }]"
            placeholder="发布状态"
            style="width: 200px; margin-left: 20px"
            :allow-clear="true"
            @change="searchNoticeByStatus"
          >
            <a-select-option v-for="(form, index) in status" :key="index" :value="form.id">{{ form.name }}</a-select-option>
          </a-select>
        </a-form-item>
      </div>
      <a-form-item style="margin-right: 0px">
        <a-button type="primary" icon="plus" @click="createNotice">新建公告</a-button>
      </a-form-item>
    </a-form>
    <a-table
      v-if="showTable"
      :columns="noticeColumns"
      :components="components"
      :data-source="noticelist"
      :loading="loading"
      :pagination="pagination"
      :customHeaderRow="headerRow"
      row-key="id"
      class="xq-draggable-table"
      @change="handleTableChange"
    >
      <span slot="customTitle" slot-scope="text, record" style="display: flex">
        <span v-if="record && record.isTop" class="showTop">置顶</span>
        <a-tooltip placement="top">
          <template slot="title">
            <span>{{ text != null ? text : "--" }}</span>
          </template>
          <div class="titleline">{{ text != null ? text : "--" }}</div>
        </a-tooltip>
      </span>
      <span slot="status" slot-scope="text">
        <span :class="text === 0 ? 'colorFF6D6D' : text === 1 ? 'tc-theme' : 'colorC0C0C0'">•</span>
        {{ text === 0 ? "待发布" : text === 1 ? "已发布" : "已下线" }}
      </span>
      <span slot="action" slot-scope="text, record">
        <span style="display: flex; align-items: center">
          <span class="edit pointer" type="link" @click="goDetail(record)">详情</span>
        </span>
      </span>
    </a-table>
    <!-- 删除公告 -->
    <a-modal
      title="删除公告"
      :visible="deleteVisible"
      class="notice-modal"
      width="468px"
      @ok="confirmDelete"
      @cancel="deleteVisible = false"
    >
      <div class="deleteline">
        <p><a-icon type="exclamation-circle" />确定删除这条公告？</p>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { formatDateAll } from "@/utils/index";
import { getSysNotices, deleteSysNotices } from "@/api/company/index";
import DraggableTableCell, { headerRow } from "@/components/DraggableTableCell";
import Sortable from "sortablejs";
const noticeColumns = [
  {
    title: "标题",
    dataIndex: "title",
    width: 260,
    onCell: () => {
      return {
        style: {
          maxWidth: 260,
          overflow: "hidden",
          whiteSpace: "nowrap",
          textOverflow: "ellipsis",
          cursor: "pointer"
        }
      };
    },
    scopedSlots: { customRender: "customTitle" }
  },
  {
    title: "状态",
    dataIndex: "status",
    width: 150,
    scopedSlots: { customRender: "status" }
  },
  {
    title: "发布时间",
    dataIndex: "publishDate",
    width: 200,
    customRender: (text, record, index) => {
      return formatDateAll(text);
    }
  },
  {
    title: "下线时间",
    dataIndex: "offlineDate",
    width: 200,
    customRender: (text, record, index) => {
      return text != null ? formatDateAll(text) : "--";
    }
  },
  {
    title: "发布范围",
    dataIndex: "publishEmpRangeIsAll",
    width: 180,
    customRender: (text, record, index) => {
      return text === true ? "全公司" : "部分员工";
    }
  },
  {
    title: "推送设置",
    dataIndex: "noticeType",
    width: 200,
    customRender: (text, record, index) => {
      const content = [];

      if (text) {
        text.split(",").forEach((element) => {
          if (element === "2") {
            content.push("短信 ");
          } else if (element === "1") {
            content.push("微信 ");
          } else if (element === "3") {
            content.push("邮件 ");
          }
        });
      } else {
        content.push("--");
      }
      return content;
    }
  },
  {
    title: "操作",
    dataIndex: "action",
    width: 180,
    scopedSlots: { customRender: "action" }
  }
];
export default {
  data() {
    this.components = {
      header: {
        cell: DraggableTableCell(noticeColumns)
      }
    };
    return {
      showTable: true,
      statusVal: null,
      loading: true,
      noticeColumns,
      searchForm: this.$form.createForm(this),
      selectedRowKeys: [],
      noticelist: [],
      deleteVisible: false,
      detailVisible: false,
      confirmLoading: false,
      companyId: "",
      currentNotice: "",
      title: null,
      status: [
        { id: 0, name: "待发布" },
        { id: 1, name: "已发布" },
        { id: 2, name: "已下线" }
      ],
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true
      }
    };
  },
  created() {
    this.companyId = this.$store.state.hr.companyId;
    this.getAllNoticelist();
  },
  mounted() {
    this.initSortable();
  },
  methods: {
    headerRow,
    initSortable() {
      new Sortable(document.getElementById("sortable_list"), {
        onEnd: this.onDragEnd
      });
    },
    onDragEnd(evt) {
      const newIndex = evt.newIndex;
      const oldIndex = evt.oldIndex;
      const columnsTemp = [...this.noticeColumns];
      const columnsMap = {};
      const initArr = [];
      for (let i = 0; i < columnsTemp.length; i++) {
        columnsMap[i] = columnsTemp[i];
        initArr.push(i);
      }
      initArr.splice(oldIndex, 1);
      initArr.splice(newIndex, 0, oldIndex);
      const columnsTempNew = initArr.map((idx) => columnsMap[idx]);
      this.noticeColumns = columnsTempNew;
      this.components = {
        header: {
          cell: DraggableTableCell(this.noticeColumns)
        }
      };
      this.showTable = false;
      this.$nextTick(() => {
        this.showTable = true;
        this.$nextTick(() => {
          this.initSortable();
        });
      });
    },
    createNotice() {
      this.$router.push({
        path: `enterprise/createNotice`,
        query: {
          sign: "0"
        }
      });
    },
    getAllNoticelist() {
      this.loading = true;
      getSysNotices({
        title: this.title,
        status: this.statusVal,
        companyId: this.companyId,
        pageSize: this.pagination.pageSize,
        pageNo: this.pagination.current
      })
        .then((res) => {
          this.noticelist = res.data.entities;
          this.pagination.total = res.data.entityCount;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.getAllNoticelist(this.currentTab);
    },
    searchContarct(e) {
      this.title = e;
      if (e) {
        getSysNotices({ companyId: this.companyId, status: this.statusVal, title: e }).then((res) => {
          this.noticelist = res.data.entities;
          this.pagination.total = res.data.entityCount;
        });
      } else {
        this.getAllNoticelist();
      }
    },
    searchNoticeByStatus(e) {
      this.statusVal = e;
      this.pagination.current = 1;
      this.getAllNoticelist();
      // getSysNotices({ companyId: this.companyId, status: e }).then(res => {
      //   this.noticelist = res.data.entities;
      //   this.pagination.total = res.data.entityCount;
      // });
    },
    check(record) {
      this.detailVisible = true;
      this.checkEleContract(record.id);
    },
    goDetail(record) {
      this.$router.push({
        path: `enterprise/createNotice`,
        query: {
          sign: "1",
          id: record.id
        }
      });
    },
    deleteNotice(record) {
      this.currentNotice = record;
      this.deleteVisible = true;
    },
    confirmDelete() {
      var companySysNoticeIds = [];
      companySysNoticeIds.push(this.currentNotice.id);
      deleteSysNotices(companySysNoticeIds).then((res) => {
        this.deleteVisible = false;
        this.$message.success("删除成功");
        this.getAllNoticelist();
      });
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    }
  }
};
</script>
<style lang="scss" scoped>
.formrow {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 20px;
  justify-content: space-between;
}

.ant-table-title {
  display: none;
}
.deleteline {
  .anticon {
    font-size: 20px;
    line-height: 30px;
    color: #faad14;
    margin-left: 10px;
  }
  p {
    font-size: 16px;
    line-height: 30px;
    margin-top: 10px;
    text-align: center;
  }
}
.showTop {
  padding: 0 5px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  line-height: 20px;
  background: #ffa600;
  border-radius: 4px;
  display: block;
  margin-right: 6px;
}
.edit {
  color: var(--primary);
}
</style>
